/**
 * @file bsp_pvd.c
 * @brief 掉电检测保护
 * @author wangh (wanghuan3037@fiberhome.com)
 * @version 1.0
 * @date 2020-11-13
 * @copyright Copyright (c) 2020  烽火通信
 ***************************************************************
 * @par 修改日志:
 * <table>
 * <tr><th>Date       <th>Version  <th>Author  <th>Description
 * <tr><td>2020-11-13 <td>1.0      <td>wangh   <td>内容
 * </table>
 */ 
#include "bsp_pvd.h"

#undef LOG_LEVEL_
#define LOG_LEVEL_  LOG_LVL_ASSERT
#include "bsp_log.h"

static pvd_handler_t pvd_handler = NULL;

#ifdef STM32F10X
#include "stm32f10x.h"

/**
 * @brief PVD初始化
 * @param  handle      掉电处理函数
 */
void pvd_init(pvd_handler_t handle)
{
    RCC_APB1PeriphClockCmd(RCC_APB1Periph_PWR, ENABLE);

    EXTI_InitTypeDef EXTI_InitStructure;
    EXTI_ClearITPendingBit(EXTI_Line16);
    EXTI_InitStructure.EXTI_Line = EXTI_Line16;
    EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt;
    EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Rising_Falling;
    EXTI_InitStructure.EXTI_LineCmd = ENABLE;
    EXTI_Init(&EXTI_InitStructure);

    NVIC_InitTypeDef NVIC_InitStructure;
    NVIC_InitStructure.NVIC_IRQChannel = PVD_IRQn;
    NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 2;
    NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
    NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
    NVIC_Init(&NVIC_InitStructure);

    if(handle)
        pvd_handler = handle;

    PWR_PVDLevelConfig(PWR_PVDLevel_2V6);   /* VDD电压低于2.6V时产生PVD中断 */
    PWR_PVDCmd(ENABLE); /* 使能PVD */
}

/**
 * @brief 掉电保护中断处理
 */
void PVD_IRQHandler(void)
{
    /*检测是否产生了PVD警告信号*/
    if (PWR_GetFlagStatus (PWR_FLAG_PVDO) == SET)
    {
        if(pvd_handler)
            pvd_handler();
    }
    EXTI_ClearITPendingBit(EXTI_Line16);    /* 清除中断信号 */
}

#elif defined GD32F10X
#include "gd32f10x.h"

void pvd_init(pvd_handler_t handle)
{
    rcu_periph_clock_enable( RCU_PMU );

    exti_init( EXTI_16, EXTI_INTERRUPT, EXTI_TRIG_BOTH );
    nvic_irq_enable( LVD_IRQn, 2, 0 );

    if(handle)
        pvd_handler = handle;

    pmu_lvd_select(PMU_LVDT_4); /* VDD电压低于2.6V时产生LVD中断 */
}

void LVD_IRQHandler(void)
{
    if(RESET != exti_interrupt_flag_get(EXTI_16))
    {
        if(pvd_handler)
            pvd_handler();

        exti_interrupt_flag_clear(EXTI_16);
    }
}
#endif

/*********** (C) COPYRIGHT 2020 FiberHome *****END OF FILE****/
